import { dom, Nodes } from '@knno/dom';
import { DialogBase } from '../dialog/dialogBase';
import { progressStyle } from './progress.css';

let waitingCount = 0;

class ProgressBox extends DialogBase {
	protected get box(): Nodes {
		return this.query(':scope>div');
	}
	protected getPanel(): Nodes {
		return this.query(':scope>div');
	}
	constructor() {
		super(
			dom
				.div(progressStyle)
				.append(
					dom.div().attr('tabindex', '0').append(dom.p('msg').css('display', 'none'), dom.progress().attr('max', '100'))
				)
		);
	}

	/**
	 * Update progress info
	 * @param value between 0 and 100
	 * @param message progress message, null or empty string will hidden message, undefined value will keep previous message state.
	 */
	update(value: number, message?: string | null) {
		const v = Math.max(Math.min(value, 100), 0);
		this.query('progress').prop('value', v);
		if (message === undefined) {
			// do nothing for message
		} else if (!message) {
			this.query('p.msg').css('display', 'none');
		} else {
			this.query('p.msg').text(message).css('display', '');
		}
	}
}

let inst: ProgressBox | null = null;

export const Progress = {
	show() {
		if (waitingCount === 0) {
			waitingCount = 1;
			inst = new ProgressBox();
			inst.show();
		} else {
			waitingCount++;
		}
	},
	close() {
		if (waitingCount > 0) {
			waitingCount--;
			if (waitingCount === 0) {
				inst?.close();
				inst = null;
			}
		}
	},
	/**
	 * Update progress info
	 * @param value between 0 and 100
	 * @param message progress message, null or empty string will hidden message, undefined value will keep previous message state.
	 */
	update(value: number, message?: string | null) {
		inst?.update(value, message);
	},
};
